package com.bawei.day12_broadcastrecevier;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.bawei.day12_broadcastrecevier.fragment.OneFragment;
import com.bawei.day12_broadcastrecevier.fragment.TwoFragment;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;

/**
 粘性广播


 */
public class Main4Activity extends AppCompatActivity implements View.OnClickListener {


    private Button bt1;
    private Button bt2;
    private OneFragment oneFragment;
    private TwoFragment twoFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);
        initView();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if(oneFragment != null){
            transaction.show(oneFragment);
        }else{
            oneFragment = new OneFragment();
            transaction.add(R.id.frame,oneFragment);
        }

        transaction.commit();


    }

    private void initView() {
        bt1 = (Button) findViewById(R.id.bt1);
        bt2 = (Button) findViewById(R.id.bt2);

        bt1.setOnClickListener(this);
        bt2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        hideAll();
        switch (v.getId()) {
            case R.id.bt1:
            {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                if(oneFragment != null){
                    transaction.show(oneFragment);
                }else{
                    oneFragment = new OneFragment();
                    transaction.add(R.id.frame,oneFragment);
                }

                transaction.commit();
            }


                break;
            case R.id.bt2:
            {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                if(twoFragment != null){
                    transaction.show(twoFragment);
                }else{
                    twoFragment = new TwoFragment();
                    transaction.add(R.id.frame,twoFragment);
                }

                transaction.commit();
            }
                break;
        }
    }

    public void hideAll(){
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if(oneFragment != null){
            transaction.hide(oneFragment);
        }
        if(twoFragment != null){
            transaction.hide(twoFragment);
        }
        transaction.commit();
    }
}
